<template>
    <div class="assignment-submissions">
      <y-header title="作业提交情况" left-arrow @click-left="onBack" />
      
      <div class="assignment-info">
        <h3>{{ assignment.title }}</h3>
        <div class="assignment-details">
          <p class="description">{{ assignment.description }}</p>
          <p class="deadline">截止日期：{{ formatDate(assignment.deadline) }}</p>
          <div class="submission-summary">
            <div class="summary-item">
              <span class="label">提交人数</span>
              <span class="value">{{ assignment.submittedCount }}/{{ assignment.totalCount }}</span>
            </div>
            <van-progress :percentage="getSubmissionPercentage(assignment)" color="#1989fa" />
          </div>
        </div>
      </div>
      
      <div class="toolbar">
        <van-search v-model="searchValue" placeholder="搜索学生姓名" />
        <van-dropdown-menu>
          <van-dropdown-item v-model="filterStatus" :options="statusOptions" />
        </van-dropdown-menu>
      </div>
      
      <div class="submissions-list">
        <van-empty v-if="filteredSubmissions.length === 0" description="暂无提交记录" />
        
        <van-cell-group v-for="submission in filteredSubmissions" :key="submission.id" inset style="margin-bottom: 12px;">
          <van-cell :title="submission.student.name">
            <template #label>
              <div class="student-info">
                <span class="student-id">学号: {{ submission.student.studentId }}</span>
                <span class="submission-time">提交时间: {{ formatDate(submission.submitTime) }}</span>
              </div>
            </template>
            <template #right-icon>
              <van-tag :type="submission.isLate ? 'warning' : 'success'">
                {{ submission.isLate ? '迟交' : '按时提交' }}
              </van-tag>
            </template>
          </van-cell>
          
          <van-cell title="评分">
            <template #value>
              <div class="grade-input">
                <van-stepper v-model="submission.score" min="0" max="100" step="1" />
                <span class="total-score">/100</span>
              </div>
            </template>
          </van-cell>
          
          <van-cell title="附件">
            <template #value>
              <div v-if="submission.attachments && submission.attachments.length > 0">
                <van-button size="small" type="primary" plain icon="download" 
                            v-for="(file, index) in submission.attachments" 
                            :key="index"
                            style="margin-right: 8px;"
                            @click="downloadFile(file)">
                  {{ file.name }}
                </van-button>
              </div>
              <span v-else>无附件</span>
            </template>
          </van-cell>
          
          <van-cell title="评语">
            <template #value>
              <van-field
                v-model="submission.comment"
                type="textarea"
                rows="2"
                placeholder="请输入评语"
                @blur="saveComment(submission)"
              />
            </template>
          </van-cell>
        </van-cell-group>
      </div>
      
      <div class="batch-actions">
        <van-button type="primary" block @click="batchSaveScores">保存所有评分</van-button>
      </div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, computed, onMounted } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { showToast, showSuccessToast } from 'vant';
  import YHeader from '@/components/YHeader.vue';
  
  interface Student {
    id: string;
    name: string;
    studentId: string;
    avatar?: string;
  }
  
  interface FileAttachment {
    id: string;
    name: string;
    url: string;
    size: number;
  }
  
  interface Submission {
    id: string;
    student: Student;
    submitTime: string;
    isLate: boolean;
    score: number;
    comment: string;
    attachments?: FileAttachment[];
  }
  
  interface Assignment {
    id: string;
    title: string;
    description: string;
    deadline: string;
    submittedCount: number;
    totalCount: number;
  }
  
  const router = useRouter();
  const route = useRoute();
  const courseId = computed(() => route.query.courseId as string);
  const assignmentId = computed(() => route.query.assignmentId as string);
  
  // 模拟数据 - 实际应该从API获取
  const assignment = ref<Assignment>({
    id: '1',
    title: '第一次作业：Vue基础',
    description: '完成Vue3组件的基本使用',
    deadline: '2023-11-20T23:59:59',
    submittedCount: 32,
    totalCount: 42
  });
  
  const submissions = ref<Submission[]>([
    {
      id: '1',
      student: {
        id: '1',
        name: '张三',
        studentId: '2021001'
      },
      submitTime: '2023-11-19T18:30:00',
      isLate: false,
      score: 95,
      comment: '完成得很好，结构清晰',
      attachments: [
        { id: '1', name: '作业1.pdf', url: '#', size: 1024 * 1024 }
      ]
    },
    {
      id: '2',
      student: {
        id: '2',
        name: '李四',
        studentId: '2021002'
      },
      submitTime: '2023-11-21T10:15:00',
      isLate: true,
      score: 85,
      comment: '部分功能实现不完整，迟交扣分',
      attachments: [
        { id: '2', name: '作业2.pdf', url: '#', size: 2048 * 1024 }
      ]
    },
    {
      id: '3',
      student: {
        id: '3',
        name: '王五',
        studentId: '2021003'
      },
      submitTime: '2023-11-20T20:45:00',
      isLate: false,
      score: 90,
      comment: '代码规范遵循得不错',
      attachments: []
    }
  ]);
  
  const searchValue = ref('');
  const filterStatus = ref('all');
  const statusOptions = [
    { text: '全部', value: 'all' },
    { text: '已提交', value: 'submitted' },
    { text: '未提交', value: 'unsubmitted' },
    { text: '迟交', value: 'late' }
  ];
  
  const filteredSubmissions = computed(() => {
    let result = submissions.value;
    
    // 搜索过滤
    if (searchValue.value) {
      const keyword = searchValue.value.toLowerCase();
      result = result.filter(
        submission => submission.student.name.toLowerCase().includes(keyword) ||
                    submission.student.studentId.toLowerCase().includes(keyword)
      );
    }
    
    // 状态过滤
    if (filterStatus.value !== 'all') {
      switch (filterStatus.value) {
        case 'submitted':
          result = result.filter(s => !s.isLate);
          break;
        case 'unsubmitted':
          // 这里实际应该显示未提交的学生
          break;
        case 'late':
          result = result.filter(s => s.isLate);
          break;
      }
    }
    
    return result;
  });
  
  onMounted(async () => {
    // 实际项目中这里应该调用API获取作业和提交情况
    // if (courseId.value && assignmentId.value) {
    //   try {
    //     const assignmentRes = await getAssignmentInfo(assignmentId.value);
    //     assignment.value = assignmentRes.data;
    //     
    //     const submissionsRes = await getSubmissionsList(assignmentId.value);
    //     submissions.value = submissionsRes.data;
    //   } catch (error) {
    //     console.error('获取数据失败', error);
    //   }
    // }
  });
  
  const onBack = () => {
    router.back();
  };
  
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  };
  
  const getSubmissionPercentage = (assignment: Assignment) => {
    if (assignment.totalCount === 0) return 0;
    return Math.round((assignment.submittedCount / assignment.totalCount) * 100);
  };
  
  const downloadFile = (file: FileAttachment) => {
    // 实际项目中这里应该实现文件下载
    showToast(`下载文件: ${file.name}`);
  };
  
  const saveComment = async (submission: Submission) => {
    // 实际项目中这里应该调用API保存评语
    showToast('评语已保存');
  };
  
  const batchSaveScores = async () => {
    // 实际项目中这里应该调用API批量保存评分
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      showSuccessToast('所有评分已保存');
    } catch (error) {
      console.error('保存评分失败', error);
      showToast('保存失败');
    }
  };
  </script>
  
  <style scoped>
  .assignment-submissions {
    background-color: #f7f8fa;
    min-height: 100vh;
    padding-bottom: 80px;
  }
  
  .assignment-info {
    background-color: #fff;
    padding: 16px;
    margin-bottom: 10px;
  }
  
  .assignment-info h3 {
    margin: 0 0 12px 0;
    font-size: 18px;
  }
  
  .assignment-details {
    color: #646566;
    font-size: 14px;
  }
  
  .assignment-details .description {
    margin: 0 0 8px 0;
  }
  
  .assignment-details .deadline {
    margin: 8px 0;
    color: #ff976a;
  }
  
  .submission-summary {
    margin: 16px 0 8px 0;
  }
  
  .summary-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
  }
  
  .toolbar {
    display: flex;
    background: #fff;
  }
  
  .toolbar .van-search {
    flex: 1;
  }
  
  .submissions-list {
    padding: 8px;
  }
  
  .student-info {
    display: flex;
    flex-direction: column;
  }
  
  .student-id {
    font-size: 13px;
  }
  
  .submission-time {
    font-size: 12px;
    color: #969799;
    margin-top: 4px;
  }
  
  .grade-input {
    display: flex;
    align-items: center;
  }
  
  .total-score {
    margin-left: 4px;
    color: #646566;
  }
  
  .batch-actions {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 16px;
    background-color: #fff;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
  }
  </style>